package com.ruoyi.zsyh.controller.applet.after.factory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.*;
import com.ruoyi.zsyh.domain.ZsyhAfterFactory;
import com.ruoyi.zsyh.domain.ZsyhAfterFactoryBalance;
import com.ruoyi.zsyh.domain.ZsyhAfterFactoryLogin;
import com.ruoyi.zsyh.domain.ZsyhAfterFactoryMenu;
import com.ruoyi.zsyh.service.*;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.*;

/**
 * 服务订单 -- 厂家
 */
@Controller
@RequestMapping("/applet/zsyh/afterFactoryBalance")
public class ZsyhAfterFactoryBalanceAppletController extends BaseController
{

    @Autowired
    private IZsyhAfterFactoryService zsyhAfterFactoryService;

    @Autowired
    private IZsyhAfterFactoryLoginService zsyhAfterFactoryLoginService;

    @Autowired
    private IZsyhAfterFactoryBalanceService zsyhAfterFactoryBalanceService;

    @Autowired
    private IZsyhAfterFactoryMenuService zsyhAfterFactoryMenuService;

    @Autowired
    private IZsyhServiceOrderService zsyhServiceOrderService;

    //微信公众号 -- 主事丫环家电维修
    @Value("${wxconfig.appIdWx}")
    private String appIdWx;
    @Value("${wxconfig.appSecretWx}")
    private String appSecretWx;

    //商户号
    @Value("${wxconfig.partner}")
    private String partner;

    //微信商户支付key
    @Value("${wxconfig.partnerKey}")
    private String partnerKey;

    //整机厂家 售后厂家充值余额回调 WX
    @Value("${wxconfig.notifyUrlAfterFactoryRecharge}")
    private String notifyUrlAfterFactoryRecharge;

    @Value("${alipay.transferAppID}")
    private String transferAppID;

    @Value("${alipay.transferPrivateKey}")
    private String transferPrivateKey;

    @Value("${alipay.transferAlipayPublicKey}")
    private String transferAlipayPublicKey;

    //整机厂家 售后厂家充值余额回调 支付宝
    @Value("${alipay.notifyUrlAfterFactoryRechargeAli}")
    private String notifyUrlAfterFactoryRechargeAli;


    /**
     * 充值获取微信的支付二维码
     * @param factoryId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getWxPayQrCode")
    @ResponseBody
    public AjaxResult getWxPayQrCode(String factoryId, String factoryLoginId, String balanceMoney, String balanceClassify)throws Exception
    {
        ZsyhAfterFactoryBalance balance = new ZsyhAfterFactoryBalance();
        balance.setFactoryId(factoryId);
        balance.setFactoryLoginId(factoryLoginId);
        balance.setBalanceMoney(new BigDecimal(balanceMoney));
        balance.setBalanceClassify(balanceClassify);
        balance.setBalanceType("1");
        balance.setBalanceOrderNum(IdWorker.getId());
        balance.setBalancePayType("1");
        zsyhAfterFactoryBalanceService.insertZsyhAfterFactoryBalance(balance);

        String description = "余额充值";
        String trade_type = "NATIVE";
        // ---必须参数
        // 商户号
        String mch_id = partner;
        // 随机字符串
        String nonce_str = StringUtils.getNonceStr();

        // 商品描述根据情况修改
        String body = description;

        // 商户订单号
        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("appid", appIdWx);
        packageParams.put("attach", "attach");
        packageParams.put("body", body);
        packageParams.put("mch_id", mch_id);
        packageParams.put("nonce_str", nonce_str);

        packageParams.put("notify_url", notifyUrlAfterFactoryRecharge);
        packageParams.put("out_trade_no", balance.getBalanceOrderNum());
        packageParams.put("spbill_create_ip", "127.0.0.1");
        packageParams.put("total_fee", balanceMoney);
        packageParams.put("trade_type", trade_type);


        RequestHandler reqHandler = new RequestHandler(null, null);
        reqHandler.init(appIdWx, appSecretWx, partnerKey);

        String sign = reqHandler.createSign(packageParams);
        String xml = "<xml>" + "<appid>" + appIdWx + "</appid>" + "<mch_id>"
                + mch_id + "</mch_id>" + "<nonce_str>" + nonce_str
                + "</nonce_str>" + "<sign>" + sign + "</sign>"
                + "<body><![CDATA[" + body + "]]></body>"
                + "<out_trade_no>" + balance.getBalanceOrderNum()
                + "</out_trade_no>" + "<attach>" + "attach" + "</attach>"
                + "<total_fee>" + balanceMoney + "</total_fee>"
                + "<spbill_create_ip>" + "127.0.0.1"
                + "</spbill_create_ip>" + "<notify_url>" + notifyUrlAfterFactoryRecharge
                + "</notify_url>" + "<trade_type>" + trade_type
                + "</trade_type>"
                + "</xml>";
        String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";


        Map map = new GetWxOrderno().getPayNoMap(createOrderURL, xml);

        System.out.println(JSONObject.toJSON(map));
        String codeUrl = String.valueOf(map.get("code_url"));
        Map data = new HashMap();
        data.put("codeUrl", codeUrl);
        data.put("balanceOrderNum", balance.getBalanceOrderNum());

        return success("成功", data);
    }


    /**
     * 充值获取支付宝支付链接
     * @param factoryId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getAliPayJson")
    @ResponseBody
    public AjaxResult getAliPayJson(String factoryId, String factoryLoginId, String balanceMoney, String balanceClassify)throws Exception
    {
        ZsyhAfterFactoryBalance balance = new ZsyhAfterFactoryBalance();
        balance.setFactoryId(factoryId);
        balance.setFactoryLoginId(factoryLoginId);
        balance.setBalanceMoney(new BigDecimal(balanceMoney));
        balance.setBalanceClassify(balanceClassify);
        balance.setBalanceType("1");
        balance.setBalanceOrderNum(IdWorker.getId());
        balance.setBalancePayType("1");
        zsyhAfterFactoryBalanceService.insertZsyhAfterFactoryBalance(balance);

        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",transferAppID,transferPrivateKey,"json","UTF-8",transferAlipayPublicKey,"RSA2");
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(notifyUrlAfterFactoryRechargeAli);
        //TODO 支付宝充值，充值后支付成果后需要返回的页面
        //部署之后才可以跳转线上链接
        request.setReturnUrl("https://dqc.zzzsyh.com/#/myWallet");
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", balance.getBalanceOrderNum());
        bizContent.put("total_amount", balance.getBalanceMoney().doubleValue());
        bizContent.put("subject", "余额充值");
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

        request.setBizContent(bizContent.toString());

        //暂时屏蔽支付
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
            logger.info("info---------------------------------------------------------支付宝支付成功response：" + JSON.toJSON(response));
        } else {
            System.out.println("调用失败");
            System.out.println(JSON.toJSON(response));
            logger.info("info---------------------------------------------------------支付宝支付失败response：" + JSON.toJSON(response));
        }



        Map data = new HashMap();
        data.put("balanceOrderNum", balance.getBalanceOrderNum());
        data.put("response", response);

        return success("成功", data);
    }

    /**
     * 获取订单的支付状态
     * @param balanceOrderNum
     * @return
     * @throws Exception
     */
    @RequestMapping("/getBalanceRechargeState")
    @ResponseBody
    public AjaxResult getBalanceRechargeState(String balanceOrderNum)throws Exception
    {
        ZsyhAfterFactoryBalance balance = zsyhAfterFactoryBalanceService.selectZsyhAfterFactoryBalanceByBalanceRechargeState(balanceOrderNum);
        return success("成功", balance.getBalanceRechargeState());
    }


}
